// 分配
var allot = allot || {};
allot.productTableId = 'scProductTable'; //产品表格ID
allot.scProOrderTableId = 'scProductOrderTable'; // 生产子订单表格
allot.allotScProOrderTableId = 'allotScProOrderTableId'; // 生产子订单表格
allot.productList = scProductList;
allot.scProOrderArr = []; // 创建的生产订单
allot.scProOrderAllotArr = []; // 分配后的生产


// 创建产品表格 初始化点击事件
allot.createProductTable = function (funcFilter) {
    var $t = $('#' + this.productTableId).find('tbody');
    $t.empty();
    for (var i in this.productList) {
        var p = this.productList[i];
        if (funcFilter && !funcFilter(p)) {
            continue;
        }
        var $trStr = $('<tr>'
            + '<td><label class="checkbox-label"><input type="checkbox" name="id" value="' + (p.id ? p.id : '') + '"></label></td>'
            + '<td>' + (p.productName ? p.productName + (ALLOT_REFUSED == p.status ? '<label class="label label-blue" title="' + (p.remark ? p.remark : '') + '">退回</label>' : '') : '') + '</td>'
            + '<td>' + (p.productAttr ? p.productAttr : '') + '</td>'
            + '<td>' + (p.businessProductName ? p.businessProductName : '') + '</td>'
            + '</tr>');
        $trStr.click(function ($event) {
            var input = $(this).find('input[type=checkbox]')[0];
            if ($event.target != input) {
                input.click();
            }
        });
        $t.append($trStr);
    }
};

// 创建生产子订单表格
allot.createScProductOrderTable = function (funcFilter) {
    var $t = $('#' + allot.scProOrderTableId).find('tbody');
    $t.empty();
    for (var i in allot.scProOrderArr) {
        var p = allot.scProOrderArr[i];
        if (funcFilter && !funcFilter(p)) {
            return;
        }
        for (var j in p.productArr) {
            var len = p.productArr.length, pr = p.productArr[j];
            var $tr = j == 0 ? $('<tr>'
                + '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '><label class="checkbox-label"><input type="checkbox" name="scProductOrderNo" value="' + (p.scProductOrderNo ? p.scProductOrderNo : '') + '"></label></td>'
                + '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '>' + (p.scProductOrderNo ? p.scProductOrderNo : '') + '</td>'
                + '<td>' + (pr.productName ? pr.productName : '') + '</td>'
                + '<td>' + (pr.productAttr ? pr.productAttr : '') + '</td>'
                + '<td>' + (pr.businessProductName ? pr.businessProductName : '') + '</td>'
                // + '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '>' + (p.allotWayName ? p.allotWayName : '') + '</td>'
                + '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '><a href="javascript:void(0)" ti data-no="' + (p.scProductOrderNo ? p.scProductOrderNo : '') + '"><span style="color: #0066ff ">取消</a></td>'
                + '< / tr > ')
                : $('<tr>'
                    + '<td>' + (pr.productName ? pr.productName : '') + '</td>'
                    + '<td>' + (pr.productAttr ? pr.productAttr : '') + '</td>'
                    + '<td>' + (pr.businessProductName ? pr.businessProductName : '') + '</td>'
                    + '< / tr > ');
            $tr.click(function ($event) {
                var input = $(this).find('input[type=checkbox]')[0];
                if (input != null && $event.target != input) {
                    input.click();
                }
            });
            $tr.find('a').click(function ($event) {
                var no = $(this).attr('data-no');
                allot.cancelScProductOrder(no);
                $event.stopPropagation();
            });
            $t.append($tr);
        }
    }
}

// 获取选择的产品ID
allot.getSelectProduct = function (funcFilter) {
    var idArr = [];
    $('#' + this.productTableId).find('tbody').find('input[type=checkbox]:checked').each(function (index, dom) {
        idArr.push($(this).val());
    });
    return idArr;
}

// 获取生产订单编号,并加入 已使用  数组
allot.getScProductOrderIdAndNo = function (callback) {
    orderNo.getIdAndNo(callback);
};

// 取消创建的生产订单
allot.cancelScProductOrder = function (no) {
    var index = -1;
    for (var i in allot.scProOrderArr) {
        if (no == allot.scProOrderArr[i].scProductOrderNo) {
            index = i;
            break;
        }
    }
    // 删除创建的订单
    allot.scProOrderArr.splice(index, 1);
    allot.createScProductOrderTable();
    /*index = -1;
     for (var i in allot.scProOrderNoUseddArr) {
     if (no == allot.scProOrderNoUseddArr[i]) {
     index = i;
     break;
     }
     }*/
    // 编号置为 未使用
    //allot.scProOrderNoUseddArr.splice(index, 1);
    orderNo.cancelUseNo(no);

    for (var i in allot.productList) {
        if (no == allot.productList[i].scProductOrderNo) {
            allot.productList[i].scProductOrderNo = null;
        }
    }
    // 重建产品表格
    allot.createProductTable(function (p) {
        return p.scProductOrderNo == null;
    });


};

// 创建生产子订单,并显示到 表格
allot.createScProductOrderAndShowTable = function () {
    var idArr = allot.getSelectProduct();
    if (idArr.length == 0) {
        DGG.Layer.message('请先选择签单产品！', {icon: '2'}, function () {
        });
        return;
    }
    // 验证签单商品的业态是否一致
    var busiArr = [];
    for (var i in idArr) {
        for (var j in this.productList) {
            var businessProductId = this.productList[j].businessProductId;
            if (idArr[i] == this.productList[j].id && (busiArr.length == 0 || businessProductId != busiArr[0])) {
                busiArr.push(businessProductId);
                break;
            }
        }
    }
    if (busiArr.length > 1) {
        DGG.Layer.message('组合时，产品的所属业态必须一致！', {icon: '2'}, function () {
        });
        return;
    }
    allot.getScProductOrderIdAndNo(function (data) {
        var productArr = [];
        for (var i in allot.productList) {
            var inArr = false, p = allot.productList[i];
            for (var j in idArr) {
                if (p.id == idArr[j]) {
                    inArr = true;
                    break;
                }
            }
            if (inArr) {
                productArr.push(p);
                p.scProductOrderNo = data.no;

            }
        }
        var scProOrder = {
            id: data.id,
            scProductOrderNo: data.no,
            productArr: productArr,
            signUserName: scOrder.signUserName,
            allotWay: null
        };
        allot.scProOrderArr.push(scProOrder);
        allot.createProductTable(function (p) {
            return p.scProductOrderNo == null;
        });
        allot.createScProductOrderTable();

    });
}

// 获取选择的 生产子订单编号
allot.getSelectScProOrderNo = function () {
    var noArr = [];
    $('#' + this.scProOrderTableId).find('tbody').find('input[type=checkbox]:checked').each(function (index, dom) {
        noArr.push($(this).val());
    });
    return noArr;
}

// 取消分配
allot.cancelAllotScProOrderNo = function (no) {
    for (var i in allot.scProOrderAllotArr) {
        var p = allot.scProOrderAllotArr[i];
        if (no == p.scProductOrderNo) {
            p.status = null;
            p.allotWayName = null;
            p.allotWay = null;
            allot.scProOrderArr.push(p);
            allot.scProOrderAllotArr.splice(i, 1);
            break;
        }
    }
    allot.createScProductOrderTable();
    allot.createAllotScProOrderTable();
}

// 创建分配后表格
allot.createAllotScProOrderTable = function (funcFilter) {
    var $t = $('#' + allot.allotScProOrderTableId).find('tbody');
    $t.empty();
    for (var i in allot.scProOrderAllotArr) {
        var p = allot.scProOrderAllotArr[i];
        if (funcFilter && !funcFilter(p)) {
            return;
        }
        for (var j in p.productArr) {
            var len = p.productArr.length, pr = p.productArr[j];
            var $tr = j == 0 ? $('<tr>'
                //+ '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '><label class="checkbox-label">'+(j+1)+'</label></td>'
                + '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '>' + (p.scProductOrderNo ? p.scProductOrderNo : '') + '</td>'
                + '<td>' + (pr.productName ? pr.productName : '') + '</td>'
                + '<td>' + (pr.productAttr ? pr.productAttr : '') + '</td>'
                + '<td>' + (pr.businessProductName ? pr.businessProductName : '') + '</td>'
                + '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '>' + (p.statusName ? p.statusName : '') + '</td>'
                //+ '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '>' + (p.flowUserName ? p.flowUserName : '') + '</td>'
                + '<td ' + (len > 1 ? 'rowspan="' + len + '"' : '') + '><a href="javascript:void(0)" ti data-no="' + (p.scProductOrderNo ? p.scProductOrderNo : '') + '"><span style="color: #0066ff ">取消</a></td>'
                + '< / tr > ')
                : $('<tr>'
                    + '<td>' + (pr.productName ? pr.productName : '') + '</td>'
                    + '<td>' + (pr.productAttr ? pr.productAttr : '') + '</td>'
                    + '<td>' + (pr.businessProductName ? pr.businessProductName : '') + '</td>'
                    + '< / tr > ');
            $tr.click(function ($event) {
                var input = $(this).find('input[type=checkbox]')[0];
                if (input != null && $event.target != input) {
                    input.click();
                }
            });
            $tr.find('a').click(function ($event) {
                var no = $(this).attr('data-no');
                allot.cancelAllotScProOrderNo(no);
                $event.stopPropagation();
            });
            $t.append($tr);
        }
        // 投标创建 额外的表格
        if (bidStatus == p.status) {
            var $tr1 = $('<tr>'
                + '<td>签单商务</td>'
                + '<td colspan="2">' + (p.signUserName ? p.signUserName : '') + '</td>'
                + '<td>签单日期</td>'
                + '<td colspan="2">' + (p.signDate ? p.signDate : '') + '</td>'
                + '< / tr > ');
            $t.append($tr1);
            var $tr2 = $('<tr>'
                + '<td>客户</td>'
                + '<td colspan="2">' + (p.customerName ? p.customerName : '') + '</td>'
                + '<td>创建时间</td>'
                + '<td colspan="2">' + (p.createTime ? p.createTime : '') + '</td>'
                + '< / tr > ');
            $t.append($tr2);
            var $tr3 = $('<tr>'
                + '<td>工时（工作日）</td>'
                + '<td colspan="2"><div class="layui-input-inline"><input name="bidWorkTime" data-index="' + i + '" type="text" class="input-style" maxlength="50"placeholder="不超过50个字符"></div></td>'
                + '<td>交付时间</td>'
                + '<td colspan="2"><div class="layui-input-inline"><input id="scProductOrder_' + i + '_bidHandOverTime" name="bidHandOverTime" data-index="' + i + '" type="text" class="Wdate input-style" maxlength="50" placeholder="不能小于当前时间"  onFocus="var scProductOrder_' + i + '_bidHandOverTime=$dp.$(this); WdatePicker({onpicked:function(){scProductOrder_' + i + '_bidHandOverTime.focus()},minDate:\'' + (new Date().format("yyyy-MM-dd hh:mm:ss")) + '\', dateFmt:\'yyyy-MM-dd\'})"></div></td>'
                + '< / tr > ');
            $tr3.find('input[type="text"]').on('input blur', function () {
                var $d = $(this), name = $d.attr('name'), index = $d.attr('data-index'), v = $d.val(),
                    isDate = $d.hasClass('Wdate');
                allot.scProOrderAllotArr[parseInt(index)][name] = v ? v : null;
            });
            $t.append($tr3);
            var $tr4 = $('<tr>'
                + '<td>合同工期</td>'
                + '<td colspan="2"><div class="layui-input-inline"><input name="bidContractTime" data-index="' + i + '" type="text" class="input-style" maxlength="50"placeholder="不超过50个字符"></div></td>'
                + '<td>需求文档</td>'
                + '<td colspan="2">' +
                '<div class="bz-upload">' +
                '<input type="hidden" value="sccenter_general_' + p.id + '_scproductorder_bid_bidFileId" id="bidFileId' + i + '">' +
                '<ul class="data-warp" id="bidFileIdPreview' + i + '">' +
                '<li>' +
                '<a href="javascript:void(0)" class="upload-button upload"></a>' +
                '<p>上传附件</p>' +
                '</li>' +
                '</ul>' +
                '</div>' +
                '</tr>');
            $tr4.find('input[type="text"]').on('input blur', function () {
                var $d = $(this), name = $d.attr('name'), index = $d.attr('data-index'), v = $d.val();
                allot.scProOrderAllotArr[parseInt(index)][name] = v ? v : null;
            });
            $tr4.find('.upload').dggUploader({
                fileId: $tr4.find('input[type="hidden"]').val(),//文件ID
                uploadBaseUrl: uploadBaseUrl,
                showIcon: true
            }).findFiles($tr4.find('input[type="hidden"]').val(), 'bidFileIdPreview' + i, 1, 0);

            $t.append($tr4);
        }
    }
}

// 发起
allot.allotScProOrder = function () {
    var noArr = allot.getSelectScProOrderNo();
    if (noArr.length == 0) {
        DGG.Layer.message(allot.scProOrderArr.length > 0 ? '请先选择生产订单！' : '请先创建生产订单！', {icon: '2'}, function () {
        });
        return;
    }
    var $box = $('#allotBox'), allotMsg = $box.serializeJson();
    allotMsg.statusName = $box.find('select[name=status]').find('option:selected').text();
    if (!allotMsg.status) {
        DGG.Layer.message('请选择发起类型！', {icon: '2'}, function () {
        });
        return;
    }
    for (var i in noArr) {
        var no = noArr[i];
        for (var j in allot.scProOrderArr) {
            var p = allot.scProOrderArr[j];
            if (no == p.scProductOrderNo) {
                p.signDate = scOrder.signDate;
                p.customerName = scOrder.customerName;
                p.status = allotMsg.status;
                p.statusName = allotMsg.statusName;
                p.createTime = new Date().format('yyyy-MM-dd hh:mm:ss');
                allot.scProOrderAllotArr.push(p);
                allot.scProOrderArr.splice(j, 1);
                break;
            }
        }
    }
    allot.createScProductOrderTable();
    allot.createAllotScProOrderTable();

}

// 初始化
allot.init = function () {
    allot.createProductTable();
    $('#createScProductOrderBtn').click(function () {
        allot.createScProductOrderAndShowTable();
    });

    $('#allotBtn').click(function () {
        allot.allotScProOrder();
    });
    $('table').find('thead').find('.checkbox-label').find('input').mouseup(function () {
        var checked = !$(this).is(':checked'),
            $inputs = $(this).parents('table').find('tbody').find('input[type=checkbox]');
        $inputs.prop({checked: checked});
    });

}


$(function () {
    DGG.Layer.loading.start();
    allot.init();
    DGG.Layer.loading.done();
});